package com.dc.di.sf.security;

import java.security.MessageDigest;

import javax.security.auth.callback.Callback;

import org.apache.ws.security.WSPasswordCallback;

public class SamplePWAuthenticationHandler implements AuthenticationHandler {

	public void authenticate(Callback callback, Object... credentials) {
		WSPasswordCallback pwcb = (WSPasswordCallback) callback;
		String id = (String) credentials[0];
		if ("test".equals(id)) {
			pwcb.setPassword(pwMd5Digest("test"));
		}
	}

	private static String pwMd5Digest(String s) {
		try {
			MessageDigest alg = MessageDigest.getInstance("MD5");
			alg.update(s.getBytes());
			byte[] digest = alg.digest();
			return byte2hex(digest);
		} catch (Exception e) {
			System.out.println(e.toString());
			return "";
		}
	}

	private static String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
		}
		return hs.toLowerCase();
	}

}
